#ifndef __M_FOMAT_H__
#define __M_FOMAT_H__

#include <iostream>
#include <ctime>
#include <sstream>
#include <cassert>
#include <vector>
#include "message.hpp"

namespace Alpaca
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, LogMsg &msg) = 0;
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << LogLevel::Tostring(msg._level);
        }
    };

    class LineFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class FileFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class ThreadFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    class LoggerFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._logger;
        }
    };

    class MsgFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S") : _time_fmt(fmt) {}

        void format(std::ostream &out, LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._time, &t);
            char tmp[32] = {0};
            strftime(tmp, sizeof(tmp) - 1, _time_fmt.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt;
    };

    class TableFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str) : _str(str) {}

        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    /*
        %d表示日期，包含子格式 {%H:%M:%S}
        %t表示线程ID
        %c表示日志器名称
        %f表示文件名
        %l表示行号
        %T表示制表符缩进
        %m表示有效载荷
        %n表示换行
    */

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _patter(pattern)
        {
            assert(ParsePattern());
        }

        std::string format(LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

        void format(std::ostream &out, LogMsg &msg)
        {
            for (auto it : _items)
            {
                it->format(out, msg);
            }
        }

        // 解析格式化规则字符串
        bool ParsePattern()
        {
            std::vector<std::pair<std::string, std::string>> fmt_order;
            int pos = 0;
            std::string key, val;
            while (pos < _patter.size())
            {
                if (_patter[pos] != '%')
                {
                    val.push_back(_patter[pos++]);
                    continue;
                }

                // 走到当前pos当前便指向一个%
                if (pos + 1 < _patter.size() && _patter[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                // 走到这说明原始字符串结束，先推送
                if (!val.empty())
                {
                    fmt_order.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 现在进行格式化字符的处理，pos指向%
                pos++;
                if (pos >= _patter.size())
                {
                    std::cout << "%后未有对应的格式化字符" << std::endl;
                    return false;
                }
                key = _patter[pos];

                // 考虑子规则的情况
                pos++;
                if (pos < _patter.size() && _patter[pos] == '{')
                {
                    pos++;
                    while (pos < _patter.size() && _patter[pos] != '}')
                    {
                        val.push_back(_patter[pos++]);
                    }

                    if (pos >= _patter.size())
                    {
                        std::cout << "子规则{}匹配出错" << std::endl;
                        return false;
                    }
                    pos++;
                }
                // 走出子规则,推送上方解析的数据
                fmt_order.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            // 根据解析到的数据，初始化成员
            for (auto &it : fmt_order)
            {
                _items.push_back(createItem(it.first, it.second));
            }
            return true;
        }

    private:
        // 根据跟时候字符创建不同的格式化对象
        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "T")
                return std::make_shared<TableFormatItem>();
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            if (key.empty())
                return std::make_shared<OtherFormatItem>(val);

            std::cout << "使用非法格式化字符: %" << key << std::endl;
            abort();
            return FormatItem::ptr();
        }

    private:
        std::string _patter; // 格式化字符串
        std::vector<FormatItem::ptr> _items;
    };
}

#endif